package com.venutech.gongan.service.impl;

import com.venutech.gongan.dao.SpGrantMapper;
import com.venutech.gongan.dao.SpGrantViewTimeSpanMapper;
import com.venutech.gongan.dao.WorkMapper;
import com.venutech.gongan.dto.rpc.common.WorkStatus;
import com.venutech.gongan.dto.rpc.common.WorkType;
import com.venutech.gongan.entity.SpGrant;
import com.venutech.gongan.entity.SpGrantViewTimeSpan;
import com.venutech.gongan.entity.Work;
import com.venutech.gongan.service.SpGrantService;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class SpGrantServiceImpl implements SpGrantService {

    private Logger logger = LoggerFactory.getLogger(SpGrantServiceImpl.class);

    @Resource
    SpGrantMapper spGrantMapper;

    @Resource
    WorkMapper workMapper;

    @Autowired
    SpGrantViewTimeSpanMapper viewTimeSpanMapper;

//    @Override
//    public int insert(SpGrantDto spGrantDto){
//        SpGrant spGrant = new SpGrant();
//        spGrant.setSp_grant_sq_user_id(spGrantDto.getUserId());
//        spGrant.setArea_code(spGrantDto.getAreaCode());
//        spGrant.setContent(spGrantDto.getContent());
//        spGrant.setWk_state(WorkStatus.InProgress.getValue());
//
//        return
//    }


    /**
     * 查找用户是否有申请过视频权限
     * @param userId
     * @param poleId
     * @param equipId
     * @return
     */
//    public boolean checkGrantedVideoPrivilege(Integer userId, Integer poleId, Integer equipId) {
//        boolean bCheckResult = false;
//        logger.info("checkGrantedVideoPrivilege: userId={}, poleId={}, equipId={}", userId, poleId, equipId);
//        SpGrant spGrant = spGrantMapper.getByPoldIdAndEquipId(userId, poleId, equipId);
//        if(Objects.nonNull(spGrant)) {
//            Work work = workMapper.getById(spGrant.getWk_id());
//            logger.info("checkGrantedVideoPrivilege: workId={}, workType={}, workState={}", work.getWk_id(), work.getWk_type(), work.getWk_state());
//            if(Objects.nonNull(work) && work.getWk_type().equals(Constants.WORK_TYPE_VIDEO_PRIVILEGE_APPLICATION) && work.getWk_state().equals(Constants.WORK_STATE_APPROVED)) {
//                logger.info("checkGrantedVideoPrivilege: bCheckResult=true");
//                bCheckResult = true;
//            }
//        }
//        return bCheckResult;
//    }

    /**
     * 查找用户视频权限
     * @param userId
     * @param equipAreaCode
     * @return
     */
    public boolean checkGrantedVideoPrivilege(Integer userId, String equipAreaCode) {
        boolean bCheckResult = false;
        logger.info("checkGrantedVideoPrivilege: userId={}, equipAreaCode={}", userId, equipAreaCode);
        List<Work> works = workMapper.getUserWorkByTypeAndStatus(WorkType.VideoPrivilegeApplication.getValue(), WorkStatus.Approved.getValue(), userId);
        if(CollectionUtils.isEmpty(works)) {
            return bCheckResult;
        }

        // 判断申请的区域
        if(!works.stream().anyMatch(w -> Strings.isNotBlank(w.getWk_area_code()) && equipAreaCode.contains(w.getWk_area_code()))) {
            return bCheckResult;
        }


        // 判断是否在申请时间 & 查看时间段内
        long currentTimestampMs = (new Date()).getTime();
        for(Work work : works) {
            SpGrant spGrant = spGrantMapper.getByWorkId(work.getWk_id());
            if(Objects.isNull(spGrant)) {
                continue;
            }
            if(Objects.isNull(spGrant.getSp_grant_start()) || Objects.isNull(spGrant.getSp_grant_end())) {
                continue;
            }
            if(currentTimestampMs < spGrant.getSp_grant_start().getTime() || currentTimestampMs > spGrant.getSp_grant_end().getTime()) {
                continue;
            }
            List<SpGrantViewTimeSpan> viewTimeSpans = viewTimeSpanMapper.getBySpGrantId(spGrant.getSp_grant_id());
            if(CollectionUtils.isEmpty(viewTimeSpans)) {
                continue;
            }
            for(SpGrantViewTimeSpan viewTimeSpan : viewTimeSpans) {
                if(currentTimestampMs >= viewTimeSpan.getTime_span_start().getTime() && currentTimestampMs <= viewTimeSpan.getTime_span_end().getTime()) {
                    logger.info("checkGrantedVideoPrivilege: bCheckResult=true, userId={}, equipAreaCode={}", userId, equipAreaCode);
                    bCheckResult = true;
                    break;
                }
            }
        }


        return bCheckResult;
    }

}
